use crate::domain::user::service;
use crate::extends::response;
use crate::extends::jwt::Claims;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json;
use tracing::info;
use jsonwebtoken::{TokenData};
use crate::extends::db::RB;
use crate::domain::user::entity::{SysUser};
use bigdecimal::BigDecimal;
use chrono::NaiveDateTime;

use rbatis::core::value::DateTimeNow;
use rbatis::core::Error;
use rbatis::crud::{CRUDMut, CRUD, Skip};
use rbatis::rbatis::Rbatis;
use serde_json::Value;
use rbatis::crud::CRUDTable;
//当前用户信息
#[fn_handler]
pub async fn profile(req: &mut Request, depot: &mut Depot, res: &mut Response) {
    
   let claims = depot.take::<TokenData<Claims>>(&"user_token_decode_data".to_owned()).claims;

   let user_id = claims.sub ;
//begin
   let mut tx = RB.acquire_begin().await.unwrap();
   let result = service::get_user_detail(&mut tx,&user_id).await ;

   match result {
       Ok(su) => {
        res.render_json(&response::success_result(&su.unwrap()));
       }
       Err(err) => {
        res.render_json(&response::fail_result(err.to_string()));
       }
   }
    //commit or rollback
    tx.commit().await.unwrap();
    
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct PutSysUser {
    pub userId: Option<String>,
    pub loginUserName: Option<String>,
    pub loginPassword: Option<String>,
    pub nickName: Option<String>,
    pub locked: Option<i32>,
}
//修改别名
#[fn_handler]
pub async fn edit_name(req: &mut Request, depot: &mut Depot, res: &mut Response) {
    
   let claims = depot.take::<TokenData<Claims>>(&"user_token_decode_data".to_owned()).claims;

   let user_id = claims.sub ;

   //begin
   let mut tx = RB.acquire_begin().await.unwrap();

   let result = tx.fetch_by_column::<SysUser,String>(&"id".to_owned(),&user_id).await;

   match result {
       Ok(mut sys_user) => {
             let putBody = req.read::<PutSysUser>().await.unwrap();
         
             //println!("putBody={:?}",&putBody);

             


             sys_user.login_user_name =Some(putBody.loginUserName.unwrap().clone());
             sys_user.nick_name =Some(putBody.nickName.unwrap().clone());
             
             println!("sys_user={:?}",&sys_user);

             let save_result =tx.update_by_column::<SysUser>(&"id".to_owned(),&sys_user).await;
             match save_result {
                 Ok(_) =>{
                    res.render_json(&response::success_result("修改成功".to_owned()));
                 }
                 Err(serr) => {
                    tx.rollback().await.unwrap();
                    res.render_json(&response::fail_result(serr.to_string()));
                 }
             }
       }
       Err(err) => {
        tx.rollback().await.unwrap();
        res.render_json(&response::fail_result(err.to_string()));
       }
   }
    
   //commit or rollback
   tx.commit().await.unwrap();
}